import * as webpack from "webpack";

import paths from "./paths";

const HtmlWebpackPlugin = require("html-webpack-plugin");
const chalk = require("chalk");
const ProgressBarPlugin = require("progress-bar-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

const isEnvProduction = process.env.NODE_ENV === "production";

const config: webpack.Configuration = {
  entry: paths.resolveApp("src/index"),
  output: {
    pathinfo: false,
  },
  resolve: {
    alias: {
      "@": paths.appSrc,
      "@pages": paths.resolveApp("src/pages"),
      "@assets": paths.resolveApp("src/assets"),
      "@components": paths.resolveApp("src/components"),
    },
    extensions: [".tsx", ".ts", ".js", ".jsx"],
  },
  module: {
    rules: [
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: "asset/resource",
        include: paths.appSrc,
      },
      {
        test: /\.(js|ts|jsx|tsx)$/,
        include: paths.appSrc,
        use: [
          {
            // loader: "esbuild-loader",
            loader: "swc-loader",
            options: {
              // esbuild 配置
              // loader: "tsx",
              // target: "es2015",
              // swc配置
              jsc: {
                parser: {
                  syntax: "typescript",
                  tsx: true,
                },
                target: "es2015",
              },
            },
          },
        ],
      },
      {
        test: /\.less$/i, // 匹配 .less 后缀的文件
        include: paths.appSrc,
        use: [
          "style-loader",
          isEnvProduction && MiniCssExtractPlugin.loader,
          {
            loader: "css-loader",
            options: {
              modules: {
                auto: true, // 只有 .module.less 文件才启用 CSS Modules
                localIdentName: "[name]__[local]___[hash:base64:5]",
              },
            },
          },
          isEnvProduction && {
            loader: "esbuild-loader",
            options: {
              loader: "css",
              minify: true, // 开启 CSS 压缩
            },
          },
          {
            loader: "postcss-loader",
            options: {
              postcssOptions: {
                plugins: [["postcss-preset-env"]],
              },
            },
          },
          "less-loader",
        ],
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      filename: "index.html",
      inject: "body",
      template: "public/index.html",
    }),
    new ProgressBarPlugin({
      format: `  :msg [:bar] ${chalk.green.bold(":percent")} (:elapsed s)`,
    }),
  ],
};

export default config;
